package com.twu.biblioteca;

import java.io.IOException;
import java.io.PrintStream;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworks
 * Date: 8/23/13
 * Time: 11:32 AM
 * To change this template use File | Settings | File Templates.
 */
public class LibraryPatrons {
    PrintStream printStream;
    List<User> patrons;
    UserInputReader userInputReader;
    Menu menu;
    private User loggedInUser =  null;

    public LibraryPatrons(PrintStream printStream, List<User> patrons, UserInputReader userInputReader, Menu menu) {
        this.printStream = printStream;
        this.patrons = patrons;
        this.userInputReader = userInputReader;
        this.menu = menu;
    }

    public void loginPrompt() throws IOException {
        String username = loginUsernamePrompt();
        String password = loginPasswordPrompt();
        validateCredentials(username, password);
    }

    public String loginUsernamePrompt() throws IOException {
        printStream.println("Enter Username");
        String username = userInputReader.readUserInput();
        return username;

    }

    public String loginPasswordPrompt() throws IOException {
        printStream.println("Enter Password");
        String password = userInputReader.readUserInput();
        return password;
    }

    public boolean validateCredentials(String username, String password) throws IOException {
        for (User patron : patrons) {
            if(patron.getUsername().equals(username) && patron.getPassword().equals(password)){
                loggedInUser = patron;
                return true;
            }
        }
        printStream.println("Incorrect credentials. Please try again.");
        loginPrompt();
        return false;
    }

    public String returnChosenOptionFromFullMenu() throws IOException {
        menu.showOptions(true);
        return userInputReader.readUserInput();
    }

    public User getLoggedInUser() {
        return loggedInUser;
    }

    public void printDetailsOrSeeLibrarian() {
        if (loggedInUser != null) {
            printMembershipDetails(loggedInUser);
        }
        else {
            printSeeLibrarian();
        }
    }

    public void printSeeLibrarian() {
        printStream.println("Please talk to a librarian.  Thank you.");
    }

    public void printMembershipDetails(User user) {
        printStream.println("Name: " + user.getName() + "\nEmail: " + user.getEmail() + "\nPhone Number: " + user.getPhoneNumber());
    }
}
